/**
 * @author p.stenzel
 */

var images = [];
var button = null;

chrome.self.onConnect.addListener(function(port)	{
	port.onMessage.addListener(function(linklist) {
		chrome.tabs.getSelected(null,function(tab)	{
			var receivingTab = tab.id;
			var sendingTab = port.tab.id;
			if(sendingTab==receivingTab)	{
				images = [];
				for(var link in linklist)	{
					images.push(linklist[link]);
				}
				if (linklist.length > 0) {
					button.innerHTML = "Browse " + linklist.length + " images";
				}	else	{
					button.innerHTML = "No imagelinks found";
				}
			}	
		})
	});
})

function registerHandlers()	{
	chrome.tabs.getSelected(null,function(tab)	{
		chrome.pageActions.enableForTab("browseImages_pa",{
			tabId: tab.id,
			url: tab.url
		});	
	})

//	for(var test in chrome.pageActions.onExecute)	{
//		console.log(test+": "+chrome.pageActions.onExecute[test]);
//	}

	chrome.pageActions.onExecute.addListener(function(pa)	{
		for(var test in pa.data)	{
			console.log(test+": "+pa.data[test]);
		}
		openImages();
	})

	button = document.getElementById("button");
	button.addEventListener("click",openImages);
	
//	chrome.tabs.onSelectionChanged(function(cb)	{
//		button.innerHTML = "Checking for imagelinks";
//	})
}

function openImages()	{
	console.log("called");
	for(var img in images)	{
		chrome.tabs.create({url:images[img]});
	}
}
